package br.edu.ufcg.sti.util.log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

public class LogBreaker {
	
	private static final long PART_LENGTH_MB = 50;
	private static final long BYTES_PER_MB = 1024 * 1024;
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		if ( args == null || args.length < 1 ) {
			throw new RuntimeException("Parametros vazios.");
		}
		
		if ( args[0] == null || args[0].equals("") ) {
			throw new RuntimeException("Parametro invalido.");
		}
		
		File f = new File( args[0] );
		if ( !f.isFile() || !f.canRead() || f.isHidden() ) {
			throw new RuntimeException("Arquivo de log invalido.");
		}

		int currentPart = 1;
		if ( args.length > 1  ) {
			try {
				currentPart = Integer.parseInt(args[1]);
			}
			catch( Exception e ) {}
		}

		InputStream is = new FileInputStream( f );
		long partBytes = PART_LENGTH_MB * BYTES_PER_MB;
		int parts = (int)Math.ceil( ((double)f.length() / (double)partBytes) );
		if( currentPart > 1 && currentPart <= parts ) {
			is.skip( (currentPart - 1) * PART_LENGTH_MB * BYTES_PER_MB );
		}
		DecimalFormat format = new DecimalFormat("00");
		
		int b;
		long count = 0;
		for(int i = currentPart; i <= parts; i++) {
			BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( new File(f.getParentFile(), f.getName() + "_part" + format.format(i)) ) );
			while ( (b = is.read()) != -1 && (++count <= partBytes ) ) {
				bos.write(b);
			}
			count = 0;
			bos.flush();			
		}
	}
}